<?php
namespace App\Http\Controllers\Api\Card;

use Carbon\Carbon;

use App\Models\ConfigureItems;  //自定义数据项配置表

use App\Service\CardService;

use App\Service\WdhService;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use App\Models\SysConfig;//系统配置表

use App\Models\Card\CardCoupon;//卡券表

use App\Models\Card\CardCouponMall;//卡券指定使用门店表

use App\Models\Goods\GoodsSaleEdit;//待发布商品表

use App\Models\Card\CardCouponCode;//卡券券码表

use App\Models\Customer\Customer; //会员表

use App\Models\Wx\WxAppletCustomer;

use App\Models\Customer\CustRank;  //会员等级表

use Illuminate\Support\Facades\Redis as Redis;

class CardController extends Controller {

    /**
     * 初始化券中心列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function init( Request $request )
    {

        $data = json_decode(Redis::get('WDH_CARD_COUPON_INIT'), true);
        if (!$data) {

            $data = [
                'group' => []
            ];

            //查询团购分组
            $group = ConfigureItems::select('item_id', 'item_name')->where(['group_id' => 1 ,'useFlg' => 1])->get()->toArray();
            if ($group) {
                foreach ($group as &$g) {
                    $data['group'][] = [
                        'id' => $g['item_id'],
                        'name' => $g['item_name']
                    ];
                }
            }

            Redis::setex('WDH_CARD_COUPON_INIT', 3600, json_encode($data, true));

        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $data]);

    }


    /**
     * 券中心卡券查询
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function search( Request $request )
    {

        $host = $request->getSchemeAndHttpHost();
        $session_id = $request->input('session_id', session_id());
        $screen_points = $request->input('screen_points');
        $screen_free = $request->input('screen_free');
        $screen_cash = $request->input('screen_cash');
        $platform = $request->input('platform', 6);

        if (empty($session_id)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);

        $where = [];
        $get_way_where = [];

        $where[] = ['start_time', '<=', Carbon::now()];
        $where[] = ['end_time', '>=', Carbon::now()];
        $where[] = ['is_center_show', 1];
        $where[] = ['useFlg' ,1];
        $where[] = ['provide_type', 1];
        if ($screen_points) {
            $get_way_where[] = 1;
        }
        if ($screen_free) {
            $get_way_where[] = 2;
        }
        if ($screen_cash) {
            $get_way_where[] = 3;
        }
        if (isset($get_way_where[0])) {
            $card = CardCoupon::where($where)->whereIn('get_way', $get_way_where)->orderBy('card_id', 'DESC')->get()->toArray();
        } else {
            $card = CardCoupon::where($where)->orderBy('card_id', 'DESC')->get()->toArray();
        }
        if ( !$card ) {
            return response()->json([ 'code' => 100003, 'message' => '没有卡券数据' ]);
        }

        $return_data = [];
        foreach ( $card as  &$item ) {

            $card_id = $item['card_id'];

            //0.未领取 1.已领取
            $code_status = 0;
            if ( $item['total_num'] <= $item['getNum'] ) { //发放总数小于已领取总数，不可领取
                $code_status = 1;
            } else if ( $item['repeat_count'] == 0 || $pcustID <= 0 ) {  //不限制领取次或没登录
                $code_status = 0;
            } else if ( $pcustID && $item['repeat_count'] > 0) { //有限制领取次数
                //获取用户已领取数量
                $use_get_amount  = CardCouponCode::where([['activity_id', $card_id], ['pcustID', $pcustID]])->count();
                if ( $use_get_amount  > 0 && $use_get_amount >= $item['repeat_count']) {
                    $code_status = 1;
                }

            }

            //折扣
            $discount = 0;
            if( $item['card_type'] == 2 ) {
                $discount = $item['discount'] * 10;
            }

            $receive_percent = 0;    //领取百分比receive_percentage：100.全部领完。0.一张未领取
            $redis_get_num = Redis::get('EBSIG_CARD_COUPON_GETED_' . $item['card_id'] ); //获取已使用的redis数据
            if ( empty( $redis_get_num ) ) {
                $redis_get_num = $item['getNum'];
            }
            if( $redis_get_num > 0 ) {
                if( $item['total_num'] <= $redis_get_num ){
                    $receive_percent = 100;
                } else {
                    $receive_percent =  number_format( $redis_get_num / $item['total_num'] , 2, "." , "") * 100;
                }
            }

            if (empty($item['card_pic'])) {
                $card_pic = '';
            } else {
                $card_pic = $host . $item['card_pic'];
            }

            $return_data[] = [
                'uuid' => $item['uuid'],
                'card_id' => $card_id,
                'group_id' => $item['item_id'],
                'card_name' => $item['card_name'],
                'card_type' => $item['card_type'],
                'card_pic' => $card_pic,
                'get_way' => $item['get_way'],
                'get_num' => $redis_get_num,
                'total_num' => $item['total_num'],
                'code_status' => $code_status,
                'receive_percent' => $receive_percent,
                'price' => $item['moneyPrice'],
                'points_price' => $item['pointsPrice'],
                'limit_money' => $item['limit_money'],
                'amount' => $item['amount'],
                'discount' => $discount,
                'end_time' => date('Y.m.d', strtotime( $item['end_time']) ),
            ];

        }

        return response()->json([
            'code' => 200 ,
            'message' => 'ok',
            'data' => [
                'list' => $return_data
            ]
        ]);

    }

    /**
     * 券中心详情页
     * @param Request $request
     * @return array
     */
    public function detail( Request $request )
    {

        $uid = $request->input('uid');
        $session_id = $request->input('session_id',session_id());
        $platform = $request->input('platform',6);

        if ( empty($uid) ) {
            return response()->json(['code'=>100001,'message'=>'缺少参数：uid']);
        }

        if ( empty($session_id) ) {
            return response()->json(['code'=>100002,'message'=>'缺少参数：session_id']);
        }

        //获取客户号
        $pcustID = get_customer_id($session_id,$platform);

        //查询字段
        $fields = [
            'uuid','card_id','card_name','card_type','time_type','use_start_time','use_end_time','valid_day','valid_begin_day','discount','amount','limit_money','end_time',
            'privilege_description','postID','salePrice','useFlg','description','repeat_count','mall_support_type','merchant_support_type','get_way','pointsPrice','moneyPrice'
        ];
        //查询卡券信息
        $card_data = CardCoupon::select($fields)->where('uuid',$uid)->first();
        if ( !$card_data) {
            return response()->json(['code'=>100003,'message'=>'卡券信息不存在']);
        }

        //转换为数组
        $card_data = collect($card_data)->toArray();

        if ( $card_data['useFlg'] == 0 ) {
            return response()->json(['code'=>100003,'message'=>'卡券已禁用']);
        }

        if ( $card_data['card_type'] == 2 ) { //折扣券
            $card_data['discount'] = $card_data['discount'] * 10 . '折' ;
        } else if ( $card_data['card_type'] == 1 || $card_data['card_type'] == 5 ) {  //代金券
            $card_data['amount'] = ($card_data['amount'] * 100) / 100; //卡券抵扣金额
        }

        $card_data['limit_money'] = ($card_data['limit_money'] * 100) / 100; //卡券使用限额

        //适用的门店或商品
        $relation_name = '不限制' ;
        // 不支持所有门店或商户
        if ( $card_data['mall_support_type'] != 1 || $card_data['merchant_support_type'] != 1 ) {

            $card_coupon_mall = CardCouponMall::select('relation_name')->where('card_id',$card_data['card_id'])->get()->toArray();
            if ( $card_coupon_mall ) {
                $relation_name = '';
                foreach ( $card_coupon_mall as $item ) {
                    if ( !$relation_name ) {
                        $relation_name = $item['relation_name'];
                    } else {
                        $relation_name .= ','.$item['relation_name'];
                    }
                }
            }
        }

        $card_data['relation_name'] = $relation_name;

        /**
         * 有效期类型：1.静态区间  2.动态时间（天）
         */
        if ( $card_data['time_type'] == 1 ) {

            $card_data['use_start_time'] = date('Y-m-d',strtotime($card_data['use_start_time']));
            $card_data['use_end_time'] = date('Y-m-d',strtotime($card_data['use_end_time']));
            $card_data['effective_time'] = date('Y.m.d',strtotime($card_data['use_end_time']));

        } else {

            $card_data['use_start_time'] = date('Y-m-d',strtotime('+' . $card_data['valid_begin_day'] . ' day')); //使用起始日期
            $card_data['use_end_time'] = date('Y-m-d',strtotime('+' . $card_data['valid_day'] . ' day',strtotime($card_data['use_start_time'])));//使用结束日期
            $card_data['effective_time'] = date('Y.m.d',strtotime('+' . $card_data['valid_day'] . ' day',strtotime($card_data['use_start_time'])));

        }

        //如果是提货券的时候标题显示商品名称
        $card_data['goodsName'] = $card_data['card_name'];
        if ( $card_data['card_type'] == 3 &&  !empty($card_data['postID']) ) {

            $goods_sale_edit = GoodsSaleEdit::select('goodsName')->where('postID',$card_data['postID'])->first();
            if ( $goods_sale_edit ) {
                $card_data['goodsName'] = $goods_sale_edit['goodsName'];
            }

        }

        if ( $pcustID ) {

            //查询券码数量
            $code_pool_amount = CardCouponCode::where([['activity_id',$card_data['card_id']],['pcustID',$pcustID]])->count();

            if ( $code_pool_amount>0 && $code_pool_amount>=$card_data['repeat_count'] ) {
                $login_status  = 2; //登录已领取完
            } else {
                $login_status  = 3; //登录未领取完
            }
        } else {
            $login_status  = 1; //未登陆
        }

        //获取系统配置信息
        $g_shop_type = SysConfig::select('config_value')->where('config_key','G_SHOP_TYPE')->first();
        $g_shop_name = SysConfig::select('config_value')->where('config_key','G_SHOP_NAME')->first();

        //返回的数据
        $return_data = [
            'card' => $card_data,//卡券信息
            'login_status' => $login_status,//页面三种状态  login_status: 1,未登录  2,登录已领取 3登录未领取
            'project_name' => !empty($g_shop_name) ? $g_shop_name['config_value'] : '',//项目名称
            'shop_type' => !empty($g_shop_type) ? $g_shop_type['config_value'] : ''//微电汇模式
        ];

        return response()->json(['code'=>200,'message'=>'ok','data'=>$return_data]);

    }

    /**
     * 券中心  领取卡券
     * @param Request $request
     */
    public function receive( Request $request )
    {

        $mobile = $request->input('mobile');
        $platform = $request->input('platform',6);
        $session_id = $request->input('session_id',session_id());
        $card_id = $request->input('card_id');

        if ( empty( $card_id ) ) {
            return response()->json(['code'=>100001,'message'=>'缺少参数：card_id']);
        }

        if ( empty( $session_id ) ) {
            return response()->json(['code'=>100002,'message'=>'缺少参数：session_id']);
        }

        $card = CardCoupon::find($card_id);
        if ( !$card ) {
            return response()->json(['code'=>100003,'message'=>'卡券信息']);
        }

        $card = $card->toArray();

        //卡券是否已被领完
        if ( $card['getNum'] == $card['total_num'] ) {
            return response()->json(['code'=>100004,'message'=>'卡券已被领完']);
        }

        $pcustID = get_customer_id($session_id, $platform);

        if ( $pcustID <=0 && empty( $mobile ) ) {
            return response()->json(['code'=>100005,'message'=>'手机号码不能为空']);
        }

        //实例卡券服务类
        $service = new CardService();

        if ( $pcustID > 0 ) {
            $customer =  Customer::select('pcustID','custID')->where('pcustID',$pcustID)->first();
        } else {
            //查询会员信息
            $customer = Customer::select('pcustID','custID')->where(['custID' => $mobile])->first();
            if ( !$customer ) {
                $customer = Customer::select('pcustID','custID')->where(['mobile' => $mobile])->first();
            }
            if ( !$customer ) {
                //获取会员等级
                $rank_data = CustRank::select('rankID','rankName')->where('useFlg',1)->orderBy('rankID', 'ASC')->first();
                if ( $rank_data ) {
                    $rankID = $rank_data['rankID'];
                    $rankName = $rank_data['rankName'];
                } else {
                    $rankID = 0;
                    $rankName = '';
                }

                $pwd = get_random_string(8, 'number');
                //注册会员
                $customer = new Customer();
                $customer->uuid = makeUuid();
                $customer->timeStamp = Carbon::now();
                $customer->creator = $mobile;
                $customer->createTime = Carbon::now();
                $customer->custID = $mobile;
                $customer->pcustID = generate_seqno('seqno_customer', '', true);
                $customer->useFlg = 1;
                $customer->custType = 1;
                $customer->rankID = $rankID;
                $customer->rankName = $rankName;
                $customer->pwd = md5($pwd);
                $customer->mobile = $mobile;
                $customer->save();
                //调用开卡接口
                WdhService::openCard([
                    'pcustID' => $customer->pcustID,
                    'custID' => $customer->custID,
                    'mobile' => $customer->mobile
                ]);
            }

            $pcustID = $customer->pcustID;
            if ( $platform == 6 ) {
                //微信小程序会员表 wx_applet_customer
                $user_info = Redis::get('WX_APPLET_USER_'.$session_id );
                if ( $user_info ) {
                    $user_info  = json_decode( $user_info,true );
                    $id = $user_info['id'];
                    $wx_applet_customer = WxAppletCustomer::find($id);
                    if ( $wx_applet_customer ) {
                        $wx_applet_customer->pcustID = $pcustID;
                        $wx_applet_customer->save();
                    }
                    $user_info['pcustID'] = $pcustID;
                    Redis::setex( 'WX_APPLET_USER_' . $session_id, 604800, json_encode( $user_info, true ) );
                }
            }
        }

        $use_get_amount  = CardCouponCode::where([['activity_id', $card_id], ['pcustID', $pcustID]])->count();

        if ( $use_get_amount >=$card['repeat_count'] ) {
            return response()->json(['code'=>100006,'message'=>'该卡券每人限领' . $card['repeat_count'] . '次！']);
        }

        $grant_result = $service->grant( $card,1,$pcustID,$customer->custID,false );
        if ( $grant_result['code'] != 200 ) {
            return response()->json(['code'=>100007,'message'=>$grant_result['message']]);
        }

        //查询卡券的总数 / 和已领取次数
        $card_data = CardCoupon::select('card_id','total_num','getNum','repeat_count')->find($card_id)->toArray();

        $redis_get_num = Redis::get('EBSIG_CARD_COUPON_GETED_' . $card_id ); //获取已使用的redis数据
        if ( empty( $redis_get_num ) ) {
            $redis_get_num = $card_data['getNum'];
        }
        //0.未领取 1.已领取
        $code_status = 0;
        if ( $redis_get_num > $card_data['total_num'] ) {
            $code_status = 1;
        } else {
            if ( $card_data['total_num'] <= $card_data['getNum'] ) { //发放总数小于已领取总数，不可领取
                $code_status = 1;
            } else if ( $card_data['repeat_count'] > 0) { //有限制领取次数
                //获取用户已领取数量
                $use_get_amount  = CardCouponCode::where([['activity_id', $card_id], ['pcustID', $pcustID]])->count();
                if ( $use_get_amount  > 0 && $use_get_amount >= $card_data['repeat_count']) {
                    $code_status = 1;
                }
            }
        }

        //领取百分比receive_percentage：100.全部领完。0.一张未领取
        $receive_percent = 0;
        if ( $redis_get_num > 0 ) {
            if ( $card_data['total_num'] <= $redis_get_num ) {
                $receive_percent = 100;
            } else {
                $receive_percent =  number_format($redis_get_num / $card_data['total_num'] , 2, "." , "") * 100;
            }
        }

        $return = [
            'card_id' => $card_id,
            'get_num' => $redis_get_num,
            'code_status' => $code_status,
            'total_num' => $card_data['total_num'],
            'receive_percent' => $receive_percent,
        ];

        return response()->json(['code'=>200,'message'=>'卡券领取成功','data' => $return]);
    }

    /**
     * 券中心领取成功页
     * @param Request $request
     * @return array
     */
    public function success (Request $request)
    {

        $card_id = $request->input('card_id');
        $session_id = $request->input('session_id');
        if ( !ebsig_is_int($card_id ) ) {
            return response()->json(['code'=>100001,'message'=>'缺少参数：card_id']);
        }

        if ( empty($session_id ) ) {
            return response()->json(['code'=>100002,'message'=>'缺少参数：session_id']);
        }

        //获取客户号
        $pcustID = 0;
        $wx_applet_info = Redis::get('WX_APPLET_USER_' .$session_id);
        if ( $wx_applet_info ) {
            $wx_applet_info =  json_decode($wx_applet_info, true);
            if (isset($wx_applet_info['pcustID']) && ebsig_is_int($wx_applet_info['pcustID'])) {
                $pcustID = $wx_applet_info['pcustID'];
            }
        }

        if ($pcustID <= 0) {
            return response()->json(['code' => 100003, 'message' => '请先登录']);
        }

        // 查询会员是否存在
        $cust_master = Customer::find($pcustID);
        if ( !$cust_master ) {
            return response()->json(['code'=>100004,'message'=>'会员信息不存在']);
        }

        //查询活动码池表信息
        $code_pool_data = CardCouponCode::select('barcode','activity_id','activity_name')
            ->where([['pcustID',$pcustID],['activity_id',$card_id]])
            ->orderBy('createTime','desc')
            ->limit(1)
            ->get()
            ->toArray();

        if ( !$code_pool_data ) {
            return response()->json(['code'=>100005,'message'=>'券码信息没有找到']);
        }

        return response()->json(['code'=>200,'message'=>'ok','data'=>$code_pool_data[0]]);

    }

}